package com.atguigu.web;

import com.atguigu.pojo.*;
import com.atguigu.service.*;
import com.atguigu.service.impl.*;
import com.atguigu.utils.WebUtils;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.*;

//前端访问这个对象,使用action,抽取数据,打包进server对象,把server对象存入serverService类,存入数据库,返回"服务器首页"
public class ServerServlet extends BaseServlet {
    ServerService serverService=new ServerServiceImpl();
    ServiceService serviceService=new ServiceServiceImpl();
    Gson gson=new Gson();
    ServerTypeService serverTypeService=new ServerTypeServiceImpl();
    ContainerVolumeMapTypeService containerVolumeMapTypeService=new ContainerVolumeMapTypeServiceImpl();
    ContainerVolumeMapService containerVolumeMapService=new ContainerVolumeMapServiceImpl();
    ContainerPortMapService containerPortMapService=new ContainerPortMapServiceImpl();

    protected void ajaxCreateServer(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String id=request.getParameter("id");
        String name=request.getParameter("name");
        String ip=request.getParameter("ip");
        String cpu=request.getParameter("cpu");
        String memory=request.getParameter("memory");
        String disk=request.getParameter("disk");
        Date endTime=WebUtils.parseStringToDate(request.getParameter("endTime"));
        String use=request.getParameter("use");
        String systemVersion=request.getParameter("systemVersion");
        String serverTypeId=serverTypeService.queryServerTypeIdByName("aliyun");

        System.out.println(id);
        if(id==null){//新增
            Server server=new Server(WebUtils.id(),name,ip,"",WebUtils.getFreePorts(""),cpu,memory,disk, endTime,systemVersion,serverTypeId,use,"");
            serverService.addServer(server);
        }else {//更新
            System.out.println("进入serverupdate,id:"+id);
            Server server=serverService.queryServerById(id);
            server.setName(name);
            server.setIp(ip);
            server.setCpu(cpu);
            server.setMemory(memory);
            server.setDisk(disk);
            server.setEndTime(endTime);
            server.setSystemVersion(systemVersion);
            server.setServerTypeId(serverTypeId);
            server.setUse(use);
            server.setMasterId("");
            serverService.updateServer(server);
        }
        //Server server=new Server(null,"济宁8","1.1.1.1","4c / 4G",500, WebUtils.parseStringToDate("20210327"));
        //serverService.addServer(server);
        response.getWriter().write("存入成功");
    }
    protected void ajaxDeleteServer(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String id=request.getParameter("id");
        Server server=serverService.queryServerById(id);
        if(server==null){
            response.getWriter().write("server id: "+id+" not found");
        }else {
            WebUtils.deleteServer(server);//欲删server,必先删service;欲删service,必先删serviceCconfig
        }
        //Server server=new Server(null,"济宁8","1.1.1.1","4c / 4G",500, WebUtils.parseStringToDate("20210327"));
        //serverService.addServer(server);
        response.getWriter().write("删除成功");
    }
    protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        List<Server> servers= serverService.queryServers();
        request.setAttribute("servers",servers);
        request.getRequestDispatcher("/pages/client/index.jsp").forward(request,response);
    }

    protected void listContainer(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String serviceId=request.getParameter("serviceId");
        String serverId=request.getParameter("serverId");
        Service service=serviceService.queryServiceById(serviceId);request.setAttribute("service",service);

        if (serverId==null) {
            if (service==null){

            }else {
                Server server=serverService.queryServerById(service.getServerId());request.setAttribute("server",server);
            }
        }else {
            Server server=serverService.queryServerById(serverId);request.setAttribute("server",server);
        }



        List<Server> servers=serverService.queryServersByServerTypeName("aliyun");request.setAttribute("servers",servers);
        List<Server> containers= serverService.queryServersByServerTypeName("docker");
        request.setAttribute("containers",containers);
        System.out.println(containers);
        request.getRequestDispatcher("/pages/client/container.jsp").forward(request,response);
    }
    protected void ajaxConfigContainer(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String id=request.getParameter("id");
        String serverId=request.getParameter("serverId");
        String serviceId=request.getParameter("serviceId");
        String name=request.getParameter("name");
        String systemVersion=request.getParameter("systemVersion");
        String cpuMemory=request.getParameter("cpuMemory");String cpu=cpuMemory.split("/")[0];String memory=cpuMemory.split("/")[1];
        String disk=request.getParameter("disk");
        String ip=request.getParameter("ip");
        String ports=request.getParameter("ports");
        String use=request.getParameter("use");
        Date endTime=WebUtils.parseStringToDate(request.getParameter("endTime"));
        String dockerServerTypeId=serverTypeService.queryServerTypeIdByName("docker");
        String masterId=request.getParameter("masterId");
        System.out.println(id);
        if (id.equals("")){
            String freePorts=WebUtils.getFreePorts("");
            Server server=new Server(WebUtils.id(),name,ip,ports,freePorts,cpu,memory,disk,endTime,systemVersion,dockerServerTypeId,use,masterId);serverService.addServer(server);
            LinkedHashMap linkedHashMap=new LinkedHashMap();linkedHashMap.put("status","添加成功");linkedHashMap.put("id",server.getId());
            response.getWriter().write(gson.toJson(linkedHashMap));
        }else {
            Server container=serverService.queryServerById(id);
            if (container==null){
                response.getWriter().write("没有这个id:"+id);
            }else {
                container.setName(name);
                container.setIp(ip);
                container.setPorts(ports);
                container.setCpu(cpu);
                container.setMemory(memory);
                container.setDisk(disk);
                container.setEndTime(endTime);
                container.setServerTypeId(dockerServerTypeId);
                container.setSystemVersion(systemVersion);
                container.setUse(use);
                container.setMasterId(masterId);
                serverService.updateServer(container);
                LinkedHashMap linkedHashMap=new LinkedHashMap();linkedHashMap.put("status","修改成功");linkedHashMap.put("id",container.getId());
                response.getWriter().write(gson.toJson(linkedHashMap));
            }
        }
    }
    protected void deleteContainer(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String id=request.getParameter("id");
        Server server = serverService.queryServerById(id);
        if (server==null){
            response.getWriter().write("没有这个id:"+id);
        }else {
            serverService.deleteServerById(id);
            response.getWriter().write("删除成功");
        }
    }

    protected void ajaxAddContainerAppendix(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String id=request.getParameter("id");
        Server container = serverService.queryServerById(id);
        if (container==null){
            response.getWriter().write("没有这个id:"+id);
        }else {
            //System.out.println(container);
            if(request.getMethod().equals("GET")){
                request.setAttribute("container",container);
                Server masterServer=serverService.queryServerById(container.getMasterId());request.setAttribute("masterServer",masterServer);
                List<ContainerVolumeMap> containerVolumeMaps=containerVolumeMapService.queryContainerVolumeMapsByContainerId(id);request.setAttribute("containerVolumeMaps",containerVolumeMaps);
                List<ContainerPortMap> containerPortMaps=containerPortMapService.queryContainerPortMapByContainerId(id);request.setAttribute("containerPortMaps",containerPortMaps);
                request.getRequestDispatcher("/pages/client/containerVolumeMap.jsp").forward(request,response);
            }else {
                String appendixs=request.getParameter("appendixs");
                //System.out.println(appendixs);
                String[] appendixsArray=appendixs.split(" ");
                ContainerVolumeMapType containerVolumeMapType=containerVolumeMapTypeService.queryContainerVolumeMapTypeByName("dir");
                containerVolumeMapService.deleteContainerVolumeMapByContainerId(id);
                containerPortMapService.deleteContainerPortMapByContainerId(id);
                for (Integer i=0;i<appendixsArray.length;i++){
                    String[] item=appendixsArray[i].split(String.valueOf('@'));
                    if (item.length==3){
                        String type=item[0];
                        String value1=item[1];
                        String value2=item[2];
                        if(type.equals("volume")){
                            ContainerVolumeMap containerVolumeMap=new ContainerVolumeMap(WebUtils.id(),id,value1,value2,"","","",containerVolumeMapType.getId());
                            containerVolumeMapService.addContainerVolumeMap(containerVolumeMap);
                        }
                        if(type.equals("port")){
                            ContainerPortMap containerPortMap=new ContainerPortMap(WebUtils.id(),id,value1,value2);
                            containerPortMapService.addContainerPortMap(containerPortMap);
                        }
                    }
                }
                response.getWriter().write("更新成功");
            }
        }
    }
    protected void deleteContainerAppendix(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String id=request.getParameter("id");
        Server container = serverService.queryServerById(id);
        if (container==null){
            response.getWriter().write("没有这个id:"+id);
        }else {
            containerVolumeMapService.deleteContainerVolumeMapByContainerId(id);
            containerPortMapService.deleteContainerPortMapByContainerId(id);
            response.getWriter().write("删除成功");
        }
    }
    protected void getTopology(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //List<Server> servers=serverService.queryServers();request.setAttribute("servers",servers);
        request.getRequestDispatcher("/pages/client/serverTopology.jsp").forward(request,response);
    }
    protected void getServers(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        List<Server> servers=serverService.queryServers();
        response.getWriter().write(gson.toJson(servers));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(Thread.currentThread().getStackTrace()[1].getFileName()+":"
                +Thread.currentThread().getStackTrace()[1].getLineNumber()+":"
                +"已经进入doget方法,"+request.getParameter("action")+" 是action名");
        doPost(request,response);//把dopost方法优化到baseServlet抽象类中去了,使得可以按照request action执行特定的方法
        //由于action判断行为在dopost中,所以在doget中执行一下dopost就可以执行判断了,从而执行特定的方法了.
    }
}
